package com.neusoft.neu24.nep.service.impl;

import com.neusoft.neu24.nep.service.INacosConsumerService;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;
import java.util.Random;

@Service
public class NacosConsumerServiceImpl implements INacosConsumerService {
//  第四步  远程服务的调用应该放在Service层 -  段静迪

    @Resource // 使用Resource 注入 DiscoveryClient ，替换Annotation @Autowired
    private DiscoveryClient discoveryClient;

    private static final Random random = new Random();

    @Override
    public String hello() {
//        第五步
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        int size = instances.size();

        ServiceInstance instance = instances.size() > 0 ? instances.get(random.nextInt(size)) : null;

        String result = WebClient.create(instance.getUri().toString())
                .get()
                .uri("/p/hello")
                .retrieve()
                .bodyToMono(String.class)
                .block();

//  原生访问
//        http://localhost:8030/p/hello
//        String result = WebClient.create("http://localhost:8031")
//                .get()
//                .uri("/p/hello")
//                .retrieve()
//                .bodyToMono(String.class)
//                .block();
        return "hello,nacos," + result;
    }
}
